<template>
  <div class="manage">
    <el-card class="box-card">
      <el-dialog
              :title="modelType === 0 ? '新增' : modelType === 1 ? '编辑' : '调薪'"
          :visible.sync="dialogVisible"
          width="50%"
          :before-close="handleClose">
        <el-form ref="form" :rules="rules" :model="form" label-width="120px" class="demo-form-inline">
          <el-form-item label="ID" prop="id">
            <el-input v-model="form.id" placeholder="ID" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="员工id" prop="userId">
            <!--            <el-input v-model="form.userId" clearable placeholder="员工id"></el-input>-->
            <el-select filterable style="width: 400px" v-model="form.userId" clearable placeholder="请选择员工">
              <el-option
                  v-for="user in userOptions"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id">
                <span style="float: left">{{ user.id }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ user.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="职位名称" prop="positionName">
            <el-input v-model="form.positionName" clearable placeholder="职位名称"></el-input>
          </el-form-item>
          <el-form-item label="基本工资" prop="baseSalary">
            <el-input v-model="form.baseSalary" type="number" clearable placeholder="基本工资"></el-input>
          </el-form-item>
          <el-form-item label="奖金" prop="bonus">
            <el-input v-model="form.bonus" type="number" clearable placeholder="奖金"></el-input>
          </el-form-item>
          <el-form-item label="社保缴费" prop="socialSecurityContribution">
            <el-input v-model="form.socialSecurityContribution" type="number" clearable
                      placeholder="社保缴费"></el-input>
          </el-form-item>
          <el-form-item label="个税缴费" prop="individualIncomeTax">
            <el-input v-model="form.individualIncomeTax" type="number" clearable placeholder="个税缴费"></el-input>
          </el-form-item>
          <el-form-item label="薪资发放日期" prop="salaryPaymentDate">
            <div class="block">
              <el-date-picker
                  v-model="form.salaryPaymentDate"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="薪资发放日期"
                  align="right"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="调薪前基本工资" prop="previousBaseSalary" v-if="modelType === 2">
            <el-input v-model="form.previousBaseSalary" type="number" clearable placeholder="调薪前基本工资"></el-input>
          </el-form-item>
          <el-form-item label="调薪后基本工资" prop="newBaseSalary" v-if="modelType === 2">
            <el-input v-model="form.newBaseSalary" type="number" clearable placeholder="调薪后基本工资"></el-input>
          </el-form-item>
          <el-form-item label="调薪原因" prop="reason" v-if="modelType === 2">
            <el-input v-model="form.reason" type="textarea" clearable placeholder="调薪原因"></el-input>
          </el-form-item>
          <el-form-item label="调薪日期" prop="adjustmentDate" v-if="modelType === 2">
            <el-date-picker
                    v-model="form.adjustmentDate"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="调薪日期"
                    align="right"
                    :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
          <!--          <el-form-item label="薪资发放日期" prop="salaryPaymentDate">-->
          <!--            <el-input v-model="form.salaryPaymentDate" clearable placeholder="薪资发放日期"></el-input>-->
          <!--          </el-form-item>-->
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
      </el-dialog>
      <div class="manage-header">
        <!--      from搜索区-->
        <el-form ref="queryForm" :inline="true" :model="queryForm" class="demo-form-inline queryForm">
          <el-form-item label="员工id" prop="userId">
            <el-input size="mini" v-model="queryForm.userId" placeholder="员工id"></el-input>
          </el-form-item>
          <el-form-item label="职位名称" prop="positionName">
            <el-input size="mini" v-model="queryForm.positionName" placeholder="职位名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="onQuerySubmit">查询</el-button>
          </el-form-item>
          <!-- 添加重置按钮 -->
          <el-form-item>
            <el-button size="mini" @click="resetQueryForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button style=" margin:0 0 10px 0" size="small" type="primary" @click="handleAdd">新增</el-button>
        <el-button style=" margin:0 0 10px 0" size="small" type="success" @click="handleAdjustSalary">调薪</el-button>
      </div>
      <div class="common-table">
        <!-- max-height="380"  -->
        <el-table
            :data="tableData"
            stripe
            style="width: 100%">
          <template slot="empty">
            <!--            <img src="../assets/iocnFonts/no-data.png" width="300"/>-->
            <div><span>暂无数据，稍后重试</span></div>
          </template>
          <el-table-column
              prop="id"
              label="ID"
              width="80">
          </el-table-column>
          <el-table-column
              prop="userId"
              label="员工姓名"
              width="180"
              :formatter="formatUserId">
          </el-table-column>
          <el-table-column
              prop="positionName"
              label="职位名称"
              width="180">
          </el-table-column>
          <el-table-column
              prop="baseSalary"
              label="基本工资"
              width="150">
          </el-table-column>
          <el-table-column
              prop="bonus"
              label="奖金"
              width="150">
          </el-table-column>
          <el-table-column
              prop="socialSecurityContribution"
              label="社保缴费"
              width="150">
          </el-table-column>
          <el-table-column
              prop="individualIncomeTax"
              label="个税缴费"
              width="150">
          </el-table-column>
          <el-table-column
              prop="salaryPaymentDate"
              label="薪资发放日期"
              width="180">
          </el-table-column>
          <!--          fixed="right"-->
          <el-table-column
              fixed="right"
              min-width="200"
              label="操作">
            <template slot-scope="scope">
              <el-button
                  type="primary"
                  plain
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                  plain
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页区-->
      <div class="block" style="margin:20px 0 0 15px ;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="tablePage.pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="tablePage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>


import {addSalary, deleteSalaryById, getSalaryById, getSalaryList, updateSalary, addAdjustment} from "@/api/Salary";
import {getUserList} from "@/api/User";

export default {
  data() {
    return {
      userOptions: [],
      dialogVisible: false,
      //表单数据
      form: {},
      queryForm: {//查询表单数据
        userId: '',
        positionName: ''
      },
      roleOptions: [
        {value: 1, label: '管理员'},
        {value: 2, label: '普通用户'}
      ],
      rules: {
        username: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '长度不小于6位数字', trigger: 'blur'}
        ]
      },
      pickerOptions: {//时间选择器
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      tableData: [],
      tablePage: {
        pageNum: 1,//当前页
        pageSize: 5,//每页条数
      },
      total: 0,
      modelType: 0
    };
  },
  created() {
    getUserList({}).then(res => {
      this.userOptions = res.data.data
    }).catch(() => {
      this.$message.error('获取数据失败')
    })
  },
  methods: {
    formatUserId(row) {
      const user = this.userOptions.find(option => option.id === row.userId);
      return user ? user.name : row.userId;
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.modelType === 0) {
            addSalary(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
                this.getList();
              } else {
                this.$message.error('操作失败，状态码：' + res.data.code);
              }
              this.$refs.form.resetFields();
              this.dialogVisible = false;
            }).catch(err => {
            });
          } else if (this.modelType === 1) {
            updateSalary(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.getList();
              } else {
                this.$message.error('操作失败，状态码：' + res.data.code);
              }
              this.$refs.form.resetFields();
              this.dialogVisible = false;
            }).catch(err => {
            });
          } else if (this.modelType === 2) {
            addAdjustment(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '调薪记录添加成功',
                  type: 'success'
                });
                this.getList();
              } else {
                this.$message.error('操作失败，状态码：' + res.data.code);
              }
              this.$refs.form.resetFields();
              this.dialogVisible = false;
            }).catch(err => {
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 弹窗关闭的时候调用
    handleClose() {
      // 清空表单
      this.form = {}
      this.dialogVisible = false
    },
    cancel() {
      this.handleClose()
    },
    handleEdit(index, row) {
      this.modelType = 1
      this.dialogVisible = true
      getSalaryById(row.id).then(res => {
        console.log(res, 'res')
        this.form = res.data.data
      }).catch(() => {
      })
    },
    handleAdjustSalary() {
      this.dialogVisible = true;
      this.modelType = 2;
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSalaryById(this.tableData[index].id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getList();
          } else {
            // 处理错误情况
            this.$message.error('操作失败，状态码：' + res.data.code);
          }
        }).catch(err => {
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleAdd() {
      this.dialogVisible = true
      this.modelType = 0
    },
    getList() {
      const params = {
        pageNum: this.tablePage.pageNum,
        pageSize: this.tablePage.pageSize,
        userId: this.queryForm.userId,
        positionName: this.queryForm.positionName
      }
      console.log(params, 'params')
      getSalaryList({params}).then(res => {
        console.log(res, 'res')
        this.tableData = res.data.data
        this.total = res.data.total || 0
      }).catch(() => {
        this.$message.error('获取数据失败')
      })
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      this.getList()//刷新数据
    },
    handleCurrentChange(currentPage) {
      this.tablePage.pageNum = currentPage
      this.getList()//刷新数据
    },
    onQuerySubmit() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          // 提交表单
          this.getList()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetQueryForm() {
      this.$refs.queryForm.resetFields();
    }
  },
  mounted() {
    this.getList()
  }
}
</script>

<style lang="less" scoped>
.manage {
  height: 90%;

  .common-table {
    position: relative;
    height: calc(100% - 50px);

    /deep/ .el-table td {
      /* 设置表格内容字体居中 */
      text-align: center;
    }

    /deep/ .el-table th {
      /* 设置表头文字居中 */
      text-align: center;
    }
  }
}
</style>
